//
//  MainViewController.m
//  VICKY ZONE
//
//  Created by sunx on 15/3/19.
//  Copyright (c) 2015年 sunx. All rights reserved.
//
#define SERVER @"http://samoyun.com/controller/blogController.php"
#define MANAGE @"http://samoyun.com/controller/mainController.php"
#define UPLOAD @"http://samoyun.com/controller/uploadController.php"
#import "SettingViewController.h"
#import "NSURLSession+KKAddition.h"
#import "ImageLoader.h"
#import "SVProgressHUD.h"

@interface SettingViewController ()
@property(nonatomic,strong) NSUserDefaults *userDefault;
@property(nonatomic,strong) NSString *username;
@property(nonatomic,strong) NSMutableString *mood;
@property(nonatomic,strong) UIAlertView *alert;
@property(strong, nonatomic) UIImagePickerController *imagePicker;
@end

@implementation SettingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithRed:92.0/255.0 green:92.0/255.0 blue:92.0/255 alpha:0.9];
    //读取用户名
    self.userDefault = [NSUserDefaults standardUserDefaults];
    self.username = [self.userDefault valueForKey:@"username"];
    
    //设置主页背景cell
    OrganicCell *setButtonCell = [OrganicCell cellWithStyle:UITableViewCellStyleDefault height:50 actionBlock:^{
        [self makeActionSheetAppear];
    }];
    setButtonCell.textLabel.text = @"HOME IMAGE";
    setButtonCell.textLabel.textAlignment = NSTextAlignmentCenter;
    setButtonCell.accessoryType  = UITableViewCellAccessoryNone;
    
    //设置主页标题cell
    OrganicCell *setTitleButtonCell = [OrganicCell cellWithStyle:UITableViewCellStyleDefault height:50 actionBlock:^{
        self.alert = [[UIAlertView alloc] initWithTitle:@"input the title" message:@"" delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:@"submit", nil];
        self.alert.alertViewStyle =  UIAlertViewStylePlainTextInput;
        [self.alert show];
    }];
    setTitleButtonCell.textLabel.text = @"HOME TITLE";
    setTitleButtonCell.textLabel.textAlignment = NSTextAlignmentCenter;
    setTitleButtonCell.accessoryType  = UITableViewCellAccessoryNone;
    
    //退出登录cell
    OrganicCell *logout = [OrganicCell cellWithStyle:UITableViewCellStyleDefault height:50 actionBlock:^{
        [self.userDefault setObject:nil forKey:@"username"];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Logout..." message:@"please restart the app to clean login message" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles: nil];
        [alert show];
    }];
    logout.textLabel.text = @"LOGOUT";
    logout.textLabel.textAlignment = NSTextAlignmentCenter;
    logout.accessoryType  = UITableViewCellAccessoryNone;
    
    //cell数组
    OrganicSection *mainSection = [OrganicSection sectionWithCells:@[setButtonCell,setTitleButtonCell,logout]];
    self.sections = @[mainSection];
}
#pragma mark - Alert Action
-(void)alertView:(UIAlertView*)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    NSLog(@"NO.%ld button",(long)buttonIndex);
    //当为cancel button 时忽略
    if(buttonIndex != 0) {
        UITextField *textField=[self.alert textFieldAtIndex:0];
        [NSURLSession POST:MANAGE pararms:@{@"user":self.username,@"home_title":textField.text} completed:^(NSData *data) {
            NSLog(@"%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
        } failed:^(NSError *error) {
            
        }];
    }
}
#pragma mark - Action Sheet
- (void)makeActionSheetAppear {
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"Change"
                                                             delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil
                                                    otherButtonTitles:@" Camera", @"Folder", nil];
    actionSheet.actionSheetStyle = UIActionSheetStyleDefault;
    [actionSheet showInView:self.view];
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSLog(@"actionSheet");
    // the user clicked one of the OK/Cancel buttons
    if (buttonIndex == 0) {
        [self pushTakePhotoScreenInDelegate];
    }
    else if (buttonIndex == 1) {
        [self pushChoosePhotoScreenInDelegate];
    }
}

-(void)pushTakePhotoScreenInDelegate
{
    self.imagePicker = [[UIImagePickerController alloc] init];
    self.imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
    self.imagePicker.delegate = self;
    [self presentViewController:self.imagePicker animated:YES completion:nil];
}

-(void)pushChoosePhotoScreenInDelegate
{
    self.imagePicker = [[UIImagePickerController alloc] init];
    self.imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    self.imagePicker.delegate = self;
    [self presentViewController:self.imagePicker animated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo
{
    [picker dismissViewControllerAnimated:YES completion:nil];
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a=[dat timeIntervalSince1970];
    NSString *timeString = [NSString stringWithFormat:@"%.0f", a];
    NSLog(@"%@",timeString);
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    NSString *filename = [NSString stringWithFormat:@"%@.png",timeString];
    NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent: filename];
    
    
    [SVProgressHUD show];
    // 保存文件的名称
    BOOL result = [UIImagePNGRepresentation(image)writeToFile: filePath    atomically:YES];
    // 保存成功会返回YES
    if(result) {
        [NSURLSession Upload:filePath user:self.username type:@"background" filename:filename progress:^(CGFloat progress) {
            
        } completed:^(NSData *data){
            [self performSelectorOnMainThread:@selector(HUDDismiss) withObject:self waitUntilDone:YES];
            NSLog(@"hahahahhahaha    ...   %@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
        } failed:^(NSError *error) {
            if(error) {
                NSLog(@"%@",error);
            }
        }];
    }
}
#pragma mark -
- (void)HUDDismiss {
    [SVProgressHUD dismiss];
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Complete..." message:@"" delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
    [alert show];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end